package com.yzh.oop3;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

/**
 * @author 于振晗
 * @title: Canteen
 * @description: TODO 食堂类
 * @date 2020年08月26日
 * @path com.yzh.oop3
 */
public class Canteen {




    public static void showEat(Programmer programmer){
        programmer.eat();
    }
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        English en = new English();
        showEat(en);

        Chinese ch = new Chinese();
        showEat(ch);

        //upcasting
        Programmer programmer = en;

        //downcasting 先做判断f
        if(programmer instanceof Chinese){
            Chinese ch1 = (Chinese)programmer;
            System.out.println("转换为中国程序员");
        }else if(programmer instanceof English){
            English en1 = (English)programmer;
            System.out.println("转换为英国程序员");
        }
        for (Class<?> c : getAllAssignedClass(Programmer.class)) {
            System.out.println(c);
        }

        ServiceLoader<Programmer> load = ServiceLoader.load(Programmer.class);
        while (load.iterator().hasNext()){
            Programmer programmer2 = load.iterator().next();

        }

    }



    public static List<Class<?>> getAllAssignedClass(Class<?> cls) throws IOException,ClassNotFoundException{
        List<Class<?>> classes = new ArrayList<Class<?>> ();
        for (Class<?> c : getClasses(cls)) {
            if (cls.isAssignableFrom(c) && !cls.equals(c)) {
                classes.add(c);
            }
        }
        return classes;
    }

    public static List<Class<?>> getClasses(Class<?> cls) throws IOException,
            ClassNotFoundException {
        String pk = cls.getPackage().getName();
        String path = pk.replace('.', '/');
        ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        URL url = classloader.getResource(path);
        return getClasses(new File(url.getFile()), pk);
    }

    /**
     * 迭代查找类
     *
     * @param dir
     * @param pk
     * @return
     * @throws ClassNotFoundException
     */
    private static List<Class<?>> getClasses(File dir, String pk) throws ClassNotFoundException {
        List<Class<?>> classes = new ArrayList<Class<?>>();
        if (!dir.exists()) {
            return classes;
        }
        for (File f : dir.listFiles()) {
            if (f.isDirectory()) {
                classes.addAll(getClasses(f, pk + "." + f.getName()));
            }
            String name = f.getName();
            if (name.endsWith(".class")) {
                classes.add(Class.forName(pk + "." + name.substring(0, name.length() - 6)));
            }
        }
        return classes;
    }
}
